import { ref } from 'vue'

const useTextOverflow = (maxLines: number) => {
  const isTextOverflow = ref(false)
  const domId = ref()

  const instance = getCurrentInstance()
  function init(_id: string) {
    domId.value = _id

    const query = uni.createSelectorQuery().in(instance)
    query
      .select(`#${domId.value}`)
      .boundingClientRect()
      .exec(([rect]) => {
        if (rect) {
          const lineHeight = 17
          const maxHeight = lineHeight * 2
          isTextOverflow.value = rect.height > maxHeight
        }
      })
  }

  const windowWidth = uni.getSystemInfoSync().windowWidth

  function textOver(text: string, size = 15) {
    const widthLength = (windowWidth - 80) / size
    const textLength = Math.floor(widthLength * maxLines)
    isTextOverflow.value = text.length > textLength
  }

  return { isTextOverflow, init, textOver }
}

export default useTextOverflow
